package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.IAdUserLoginService;
import com.heima.model.admin.dtos.LoginDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
* @author Administrator
* @description 针对表【ad_user(管理员用户信息表)】的数据库操作Service实现
* @createDate 2024-08-21 11:23:33
*/
@Service
@RequiredArgsConstructor
public class AdUserLoginLoginServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements IAdUserLoginService {

    private final AdUserMapper adUserMapper;

    @Override
    public ResponseResult login(LoginDto loginDto) {
        //通过用户名查询用户数据
        Map<String, Object> map = new HashMap<>();
        if (!StringUtils.isEmpty(loginDto.getName()) && !StringUtils.isEmpty(loginDto.getPassword())) {
            AdUser adUser = adUserMapper.selectOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName,loginDto.getName()));
            if (adUser == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"数据不存在");
            }
            //输入密码+salt  再来MD5
            String salt = adUser.getSalt();
            String inputPwd = DigestUtils.md5DigestAsHex((loginDto.getPassword()+salt).getBytes());
            //比较密码
            if(!inputPwd.equals(adUser.getPassword())){
                return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
            }
            //生成token 构造返回数据
            adUser.setPassword("");
            adUser.setSalt("");
            map.put("user", adUser);
            map.put("token", AppJwtUtil.getToken(adUser.getId().longValue()));
        }
        return ResponseResult.okResult(map);
    }
}




